import { useRequest } from 'ahooks';
import { Layout, Row } from 'antd';
import { Content } from 'antd/es/layout/layout';
import { memo, useEffect, useState } from 'react';
import { Route, Routes } from 'react-router-dom';
import { Web3 } from 'web3';

import { getIncomeOffers, getOutgoingOffers } from '../../api/walletsAPI.ts';
import { chainList } from '../../utils';

import { PageMainHeader } from './components/Header/PageMainHeader.tsx';
import { PageMainSider } from './components/Sider/PageMainSider.tsx';
import { usePageMainStyles } from './styles.tsx';
import { TabBarter } from './tabs/Barter/TabBarter.tsx';
import { TabMyNFTs } from './tabs/MyNFTs/TabMyNFTs.tsx';
import { TabNFTGallery } from './tabs/NFTGallery/TabNFTGallery.tsx';

import type { Offer } from '../../types.ts';

type ChainId = keyof typeof chainList;

export const PageMain = memo(() => {

    const { styles } = usePageMainStyles();

    const [chainName, setChainName] = useState('unknown');

    const { loading: loadingOutgoingData, data: outgoingData } =  useRequest(getOutgoingOffers);
    const { loading: loadingIncomeData, data: incomeData } =  useRequest(getIncomeOffers);

    useEffect( () => {
        const web3 = new Web3(window.ethereum);
        web3.eth.getChainId().then(chainId => {
            setChainName(chainList[chainId.toString() as ChainId] || 'unknown');
        });

    }, []);

    return (
        <div className={styles.page}>
            <PageMainHeader chainName={chainName}/>
            <Content className={styles.content}>
                <Row justify="center" align="middle">
                    <Layout>
                        <PageMainSider incomeOffers={!!incomeData?.length} />
                        <Routes>
                            <Route path="/" element={<TabMyNFTs/>} />
                            <Route path="/barter" element={(loadingOutgoingData && loadingIncomeData) ? 'LOADING...' : <TabBarter outgoingOffers={outgoingData as Offer[]} incomeOffers={incomeData as Offer[]}/>} />
                            <Route path="/search" element={<TabNFTGallery />}/>
                            <Route path="*" element={<div>404</div>}/>
                        </Routes>
                    </Layout>
                </Row>
            </Content>
        </div>
    );
});

